import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { maService } from '../../../../service/ma/ma.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import {insService} from "../../../../service/ins/ins.service";
import {ProductService} from "../../../../service/prod/product.service";
import {fileService} from "../../../../service/file/file.service";

@Component({
  selector: 'file-add',
  templateUrl: './file-add.component.html',
  styleUrls: ['./file-add.component.less']
})
export class fileAddComponent implements OnInit, OnDestroy {
  product:  any = {
    id:null,
    fileNo: null,
    bpmStatus:"1",
    fileName: null,
    fileStatus: "已上传",
    fileOwner: null,
    fileNowOwner: null /*No show*/,
    fileFrom: null,
    fileTo: null,
    fileRemark: null
  };




  bpmStatus =  [{text: '我的', value: '1'}, {text: '已发送', value: '10'}, {text: '已接收', value: '20'}];

  MAX_COUNT = 60;
  tabIndex = 0;
  saleing = false;
  private sub: any;

  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;

  uploadUrl = '';
  avatarParam = { sbtype: 'No',  filetype:'file',orderNo: 'no'};
  fileList = [ ];
  avatarUrl:string;
  loading = false;

  sysusers=[];
  constructor(
    private productService: ProductService,

    public setting: SettingsService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private fileService: fileService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private cnt: Constant,
    private router: Router,
    private comm: CommService
  ) {}

  ngOnInit(): void {

    // this.loadbpmStatus();
    this.loadsysusers();

    this.uploadUrl = this.fileService.uploadUrl();
    this.comm.getfileno("order").pipe().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      console.log("string******fiel"+JSON.stringify(data));
      this.product.fileNo =  ret['data'];
      this.avatarParam = { sbtype: 'No',  filetype:'file',orderNo: this.product.fileNo};
      this.product.fileOwner = this.setting.user.username;
      this.product.fileNowOwner = this.setting.user.username;
      this.product.fileFrom = this.setting.user.username;
      // this.product.fileTo = this.setting.user.username;

    });

    // 隐藏reusetab
    setTimeout(() => {
      this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 1000);
  }

  // 显示reusetab
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  changeTab(index) {
    // 使用异步的方式更新组件, 防止ngIf错误
    Promise.resolve(null).then(() => this.tabIndex = index);
  }


  // 加载证件类型
  loadsysusers() {
    this.sysusers = [];
    this.comm.getsysusers(this.setting.user.sysorgCode).subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.sysusers.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }





  back() {
    this.router.navigate(['/file/file']);
  }


  save() {
    if(this.product.fileNo===''||this.product.fileNo===null){
      this.msg.warning("请返回重新点击添加");
      return;
    }
    if(this.product.fileName===''||this.product.fileName===null){
      this.msg.warning("文件名字");
      return;
    }
    let fxjFileMainPage = {
      createBy:this.setting.user.username,
      sysOrgCode:this.setting.user.sysorgCode,

      fileNo: this.product.fileNo,
      fileName: this.product.fileName,
      fileStatus: this.product.fileStatus,
      fileOwner: this.product.fileOwner,
      fileNowOwner: this.product.fileNowOwner, /*No show*/
      fileFrom: this.product.fileFrom,
      fileTo: this.product.fileTo,
      fileRemark: this.product.fileRemark
      // fiOperDate: this.product.fiOperDate /*No show*/
    };

    // 调用接口
    this.fileService.addfile(fxjFileMainPage).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      if (data.ok === true) {
        this.product.fileNo="";
        this.msg.success('新增成功');
        this.emit.sendMessage("RELOAD_GOODS_LIST");
      } else {
        this.msg.error(data['message']);
      }
    })
  }

  changeColor(res) {
    this.product.colorSort = res.color.hex;
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      this.msg.warning('图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }

  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl = img;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }
}
